<?php
namespace app\wechatxcx\controller;

use app\common\model\User;
use app\common\model\UserLoginstatus;
use app\common\model\UserWechat;
use app\libs\WXBizDataCrypt;
use app\service\LoginService;

class Login extends AllBase
{
    public $openPlatform;
    public function __construct () {
        parent::__construct();
    }

    public function phone()
    {
        //表单信息
        $encryptedData = input('encryptedData');
        $iv = input('iv');
        $code = input('code');
        $secret = config('xiaochengxu_secret');
        $appid = config('xiaochengxu_appid');

        //交换session_key和openid
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";
        $response = file_get_contents($url);
        $data = json_decode($response,true);

        $openid = $data['openid'];
        $sessionKey = $data['session_key'];

        //获取手机号码
        $data = null;
        $pc = new WXBizDataCrypt($appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data );
        $data = json_decode($data,true);

        $phone = $data['phoneNumber'];


        //获取用户信息
        $this->user = User::getOne(array('mobile' => $phone));
        //用户信息不存在，新建
        if(!$this->user){
            //用户信息
            $user_save = array(
                'mobile' => $phone,
                'create_time' => time(),
                'update_time' => time(),
                "openid_main"=>$openid
            );
            $uid = User::insertGetId($user_save);

            //用户微信信息
            $user_wechat_save = array(
                'uid'=>$uid,
                'openid'=>$openid,
                'create_time' => time(),
                'update_time' => time()
            );
            UserWechat::setInsertGetId($user_wechat_save);

            //登录状态
            $user_loginstatus_save = array(
                'uid'=>$uid,
                'session_token'=>createPassword(uniqid().time().$uid),
                'create_time' => time(),
                'update_time' => time(),
                'expire_time'=>time()+7*24*3600
            );
            UserLoginstatus::setInsertGetId($user_loginstatus_save);
            $session_token = $user_loginstatus_save['session_token'];
        }else{
            //登录状态
            $user_loginstatus_save = array(
                'session_token'=>createPassword(uniqid().time().$this->user['id']),
                'update_time' => time(),
                'expire_time'=>time()+7*24*3600
            );
            UserLoginstatus::update($user_loginstatus_save,array('uid'=>$this->user['id']));
            $session_token = UserLoginstatus::getValue(array('uid'=>$this->user['id']),'session_token');
        }
        return returnJson(200, '', $session_token);

    }

    //微信登陆
    public function wechat(){
        $input = input();
        $input['mall_id']= 1;
//        if(!$input['url'] || !$input['mall_id']) {
//            _pr('error');
//        }
        if($input['url']) {
            $url = $input['url'];
            $url = str_replace('%26','&',$url);
            $url .= '&mall_id=1';
            cookie('redirect_url',$url);
        }
        //$officialAccount = $this->openPlatform->officialAccount($this->mall['authorizer_appid'],$this->mall['authorizer_refresh_token']);
        $officialAccount = $this->officialAccount;
        $oauth = $officialAccount->oauth->scopes(['snsapi_userinfo']);
        return $oauth->redirect()->send();
    }



    //微信回调
    public function wechat_callback(){
        cookie('user_id',null);
        $officialAccount = $this->officialAccount;
        //$officialAccount = $this->openPlatform->officialAccount($this->mall['authorizer_appid'],$this->mall['authorizer_refresh_token']);
        $user = $officialAccount->oauth->user()->toArray();
        $wechatUser = $user['original'];
        $wechatUser['mall_id'] = $this->mall['id']?$this->mall['id']:1;

        $apiUserInfo = $officialAccount->user->get($wechatUser['openid']);//接口获取的用户信息包含是否关注
        $wechatUser['subscribe'] = $apiUserInfo['subscribe'];

        $user_id = UserService::S()->handleWechatUser($wechatUser);
        cookie('user_id',$user_id);
        $userInfo = User::getOneById($user_id);
        /* if(!$userInfo['openid_main']) {
            $config = [
                'app_id'   => config('open_appid'),
                'secret'   => config('open_secret'),
                'token'    => config('open_token'),
                'aes_key'  => config('open_aeskey'),
                'oauth' => [
                    'scopes'   => ['snsapi_base'],
                    'callback' => '/api/login/wechat_callback_main',
                ]
            ];
            $this->openPlatform=Factory::openPlatform($config);
            $mallInfo = Mall::getOneById(1);
            $officialAccount = $this->openPlatform->officialAccount($mallInfo['authorizer_appid'],$mallInfo['authorizer_refresh_token']);
            $oauth = $officialAccount->oauth->scopes(['snsapi_base']);
            return $oauth->redirect()->send();
        } */
        //$user_id=2;
        $token=LoginService::S()->checkStatus($user_id);
        cookie('session_token',$token, 300);
        $url  =  cookie('redirect_url');
		$this->redirect($url);
        //header('Location: '.);exit;
    }

    /* 所有分公司都用mall_id=1的信息做一次授权记录openid */
    public function wechat_callback_main () {
        $user_id = cookie('user_id');
        $mallInfo = Mall::getOneById(1);
        $officialAccount = $this->openPlatform->officialAccount($mallInfo['authorizer_appid'],$mallInfo['authorizer_refresh_token']);
        $user = $officialAccount->oauth->user()->toArray();
        $wechatUser = $user['original'];

        User::where(['id'=>$user_id])->update([
            'openid_main' => $wechatUser['openid']
        ]);

        $token=LoginService::S()->checkStatus($user_id);
        $url  =  cookie('redirect_url')."&session_token={$token}";
        $this->redirect($url);
    }

    /* 检查登录态 */
    public function checkToken () {
        $input = input();

        if(!$input['session_token']) {
            $this->ajax(203,'正在登陆...');
        }

        $loginstatus = UserLoginstatus::getOne(array('session_token'=>$input['session_token']));
        if($loginstatus['expire_time']<time()){

            $this->ajax(203,'正在登陆...');
        }

        $this->ajax(200,'success');
    }
}
